package cn.kwq.project_manger.aop.aspect;

import cn.kwq.project_manger.aop.annotations.LimitRequest;
import cn.kwq.project_manger.common.E;
import cn.kwq.project_manger.common.R;
import cn.kwq.project_manger.exception.RequestLimitException;
import cn.kwq.project_manger.utils.IPUtils;
import lombok.extern.slf4j.Slf4j;
import net.jodah.expiringmap.ExpirationPolicy;
import net.jodah.expiringmap.ExpiringMap;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.UndeclaredThrowableException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * 防盗刷 ExpiringMap版本，不带redis
 */
@Aspect
@Component
@Slf4j
public class LimitRequestAspect {

    private static ConcurrentHashMap<String, ExpiringMap<String, Integer>> connMap = new ConcurrentHashMap<>();

    // 定义切点
    // 让所有有@LimitRequest注解的方法都执行切面方法
    @Pointcut("@annotation(limitRequest)")
    public void excudeService(LimitRequest limitRequest) {
    }

    @Around(value = "excudeService(limitRequest)", argNames = "pjp,limitRequest")
    public Object doAround(ProceedingJoinPoint pjp, LimitRequest limitRequest) throws Throwable {

        // 获得request对象
        RequestAttributes req = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sReq = (ServletRequestAttributes) req;
        HttpServletRequest request = sReq.getRequest();

        //获取发起请求的真实ip地址，作为缓存map的key
        String ipAddr = IPUtils.getIpAddr(request);
        //获取请求的路径作为key
        String requestURI = request.getRequestURI();

        // 获取Map对象， 如果没有则返回默认值
        // 第一个参数是key， 第二个参数是默认值
        ExpiringMap<String, Integer> cache = connMap.getOrDefault(requestURI, ExpiringMap.builder().variableExpiration().build());

        //获取请求次数
        Integer reqCount = cache.getOrDefault(ipAddr, 0);


            if (reqCount >= limitRequest.count()) {
                // 请求超过次数，不执行目标方法
                log.warn("["+ipAddr+"]"+"请求"+"["+requestURI+"]"+"超过次数");
                throw new RequestLimitException(limitRequest.msg());
            } else if (reqCount == 0){
                // 第一次请求时，设置缓存有效时间
                cache.put(ipAddr, reqCount + 1, ExpirationPolicy.CREATED, limitRequest.time(), TimeUnit.MILLISECONDS);
            } else { // 未超过次数， 记录加一
                cache.put(ipAddr, reqCount + 1);
            }
            connMap.put(requestURI, cache);



        // result的值就是被拦截方法的返回值
        Object result = pjp.proceed();

        return result;
    }


}
